package com.example.user.controller;

import com.example.user.entity.User;
import com.example.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @GetMapping("/search")
    public User findByEmail(@RequestParam String email) {
        return userService.findByEmail(email);
    }

    @PutMapping("/{id}")
    public void update(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.update(user);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        userService.delete(id);
    }

    @PostMapping
    public ResponseEntity<String> addUser(@RequestBody User user) {
        // 打印接收到的用户信息
        System.out.println("Received user: " + user.getUsername() + ", " + user.getEmail());

        if (userService.userExists(user.getEmail())) {
            return ResponseEntity.status(400).body("User already exists");
        } else {
            userService.save(user);
            return ResponseEntity.ok("User saved successfully");
        }
    }

}
